package com.netty.io.nio;

import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.*;
import java.util.Iterator;
import java.util.Set;

public class NioSelectorServerExample {

    public static void main(String[] args) throws Throwable{

        //server端开启channel
        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();

        //selector开启
        Selector selector = Selector.open();

        //server端的channel绑定监听端口
        serverSocketChannel.bind(new InetSocketAddress(6666));

        //设置channel为非阻塞模式
        serverSocketChannel.configureBlocking(false);

        //server注册到selector上(关注事件是OP_ACCEPT连接事件)
        serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);

        while (true){
            if(selector.select(1000) == 0){//没有事件发生
                System.out.println("服务器等待1秒，无连接");
                continue;
            }

            //获取事件selectionKeys
            Set<SelectionKey> selectionKeys = selector.selectedKeys();
            Iterator<SelectionKey> iterator = selectionKeys.iterator();
            while (iterator.hasNext()){
                SelectionKey selectionKey = iterator.next();
                //判断连接事件的类型，如果是client连接上的event
                if(selectionKey.isAcceptable()){
                    //client已连接上server端，获取到client端的channel
                    SocketChannel socketChannel = serverSocketChannel.accept();
                    socketChannel.configureBlocking(false);
                    //将client端的channel注册到selector,同时新开一个buffer缓冲区
                    socketChannel.register(selector,SelectionKey.OP_READ, ByteBuffer.allocate(1024));
                    System.out.println("连接上了...");
                }
                //判断连接事件的类型，如果是可以读取通信的event
                if(selectionKey.isReadable()){
                    //client已经注册好，成为可通信状态,从selectorKey获取到client注册的channel
                    SocketChannel channel = (SocketChannel)selectionKey.channel();
                    ByteBuffer byteBuffer = (ByteBuffer) selectionKey.attachment();
                    //将channel的数据读取到byteBuffer
                    int read = channel.read(byteBuffer);
                    System.out.println("客户端发送的数据:" + new String(byteBuffer.array(),0,read));
                }

                //处理过的selectorKey要删除掉，避免重复处理
                iterator.remove();
            }
        }

    }
}
